import 'package:flutter/material.dart';
import '../../config/theme/theme_manager.dart';

/// 通用加载组件
/// 提供多种加载样式和配置选项
class CommonLoading extends StatelessWidget {
  /// 加载样式
  final LoadingStyle style;

  /// 加载大小
  final LoadingSize size;

  /// 自定义颜色
  final Color? color;

  /// 加载文本
  final String? text;

  /// 文本样式
  final TextStyle? textStyle;

  /// 是否显示背景
  final bool showBackground;

  /// 背景颜色
  final Color? backgroundColor;

  /// 背景透明度
  final double backgroundOpacity;

  /// 内边距
  final EdgeInsetsGeometry? padding;

  /// 外边距
  final EdgeInsetsGeometry? margin;

  /// 圆角半径
  final double? borderRadius;

  const CommonLoading({
    super.key,
    this.style = LoadingStyle.circular,
    this.size = LoadingSize.medium,
    this.color,
    this.text,
    this.textStyle,
    this.showBackground = false,
    this.backgroundColor,
    this.backgroundOpacity = 0.8,
    this.padding,
    this.margin,
    this.borderRadius,
  });

  @override
  Widget build(BuildContext context) {
    final themeManager = ThemeManager.instance;
    final loadingColor = color ?? themeManager.primaryColor;

    Widget loadingWidget = _buildLoadingWidget(loadingColor);

    if (text != null) {
      loadingWidget = Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          loadingWidget,
          const SizedBox(height: 12),
          Text(
            text!,
            style: textStyle ??
                TextStyle(
                  fontSize: 14,
                  color: themeManager.contrastColor,
                ),
          ),
        ],
      );
    }

    if (showBackground) {
      loadingWidget = Container(
        padding: padding ?? const EdgeInsets.all(20),
        margin: margin,
        decoration: BoxDecoration(
          color: (backgroundColor ?? themeManager.cardColor)
              .withOpacity(backgroundOpacity),
          borderRadius: BorderRadius.circular(borderRadius ?? 12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 10,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: loadingWidget,
      );
    }

    return loadingWidget;
  }

  /// 构建加载组件
  Widget _buildLoadingWidget(Color loadingColor) {
    final double loadingSize = _getLoadingSize();

    switch (style) {
      case LoadingStyle.circular:
        return SizedBox(
          width: loadingSize,
          height: loadingSize,
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(loadingColor),
            strokeWidth: _getStrokeWidth(),
          ),
        );
      case LoadingStyle.linear:
        return SizedBox(
          width: loadingSize * 2,
          child: LinearProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(loadingColor),
            backgroundColor: loadingColor.withOpacity(0.2),
          ),
        );
      case LoadingStyle.dots:
        return _DotsLoading(
          color: loadingColor,
          size: loadingSize / 6,
        );
      case LoadingStyle.pulse:
        return _PulseLoading(
          color: loadingColor,
          size: loadingSize,
        );
      case LoadingStyle.wave:
        return _WaveLoading(
          color: loadingColor,
          size: loadingSize,
        );
    }
  }

  /// 获取加载大小
  double _getLoadingSize() {
    switch (size) {
      case LoadingSize.small:
        return 20;
      case LoadingSize.medium:
        return 30;
      case LoadingSize.large:
        return 40;
      case LoadingSize.extraLarge:
        return 50;
    }
  }

  /// 获取线条宽度
  double _getStrokeWidth() {
    switch (size) {
      case LoadingSize.small:
        return 2;
      case LoadingSize.medium:
        return 3;
      case LoadingSize.large:
        return 4;
      case LoadingSize.extraLarge:
        return 5;
    }
  }
}

/// 加载样式
enum LoadingStyle {
  circular,
  linear,
  dots,
  pulse,
  wave,
}

/// 加载大小
enum LoadingSize {
  small,
  medium,
  large,
  extraLarge,
}

/// 点状加载动画
class _DotsLoading extends StatefulWidget {
  final Color color;
  final double size;

  const _DotsLoading({
    required this.color,
    required this.size,
  });

  @override
  State<_DotsLoading> createState() => _DotsLoadingState();
}

class _DotsLoadingState extends State<_DotsLoading>
    with TickerProviderStateMixin {
  late List<AnimationController> _controllers;
  late List<Animation<double>> _animations;

  @override
  void initState() {
    super.initState();
    _controllers = List.generate(
      3,
      (index) => AnimationController(
        duration: const Duration(milliseconds: 600),
        vsync: this,
      ),
    );

    _animations = _controllers.map((controller) {
      return Tween<double>(begin: 0.0, end: 1.0).animate(
        CurvedAnimation(parent: controller, curve: Curves.easeInOut),
      );
    }).toList();

    _startAnimations();
  }

  void _startAnimations() {
    for (int i = 0; i < _controllers.length; i++) {
      Future.delayed(Duration(milliseconds: i * 200), () {
        if (mounted) {
          _controllers[i].repeat(reverse: true);
        }
      });
    }
  }

  @override
  void dispose() {
    for (final controller in _controllers) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(3, (index) {
        return AnimatedBuilder(
          animation: _animations[index],
          builder: (context, child) {
            return Container(
              margin: EdgeInsets.symmetric(horizontal: widget.size * 0.2),
              width: widget.size,
              height: widget.size,
              decoration: BoxDecoration(
                color: widget.color
                    .withOpacity(0.3 + _animations[index].value * 0.7),
                shape: BoxShape.circle,
              ),
            );
          },
        );
      }),
    );
  }
}

/// 脉冲加载动画
class _PulseLoading extends StatefulWidget {
  final Color color;
  final double size;

  const _PulseLoading({
    required this.color,
    required this.size,
  });

  @override
  State<_PulseLoading> createState() => _PulseLoadingState();
}

class _PulseLoadingState extends State<_PulseLoading>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );

    _animation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
    );

    _controller.repeat(reverse: true);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        return Container(
          width: widget.size,
          height: widget.size,
          decoration: BoxDecoration(
            color: widget.color.withOpacity(0.3 + _animation.value * 0.7),
            shape: BoxShape.circle,
          ),
        );
      },
    );
  }
}

/// 波浪加载动画
class _WaveLoading extends StatefulWidget {
  final Color color;
  final double size;

  const _WaveLoading({
    required this.color,
    required this.size,
  });

  @override
  State<_WaveLoading> createState() => _WaveLoadingState();
}

class _WaveLoadingState extends State<_WaveLoading>
    with TickerProviderStateMixin {
  late List<AnimationController> _controllers;
  late List<Animation<double>> _scaleAnimations;
  late List<Animation<double>> _opacityAnimations;

  @override
  void initState() {
    super.initState();
    _controllers = List.generate(
      4,
      (index) => AnimationController(
        duration: const Duration(milliseconds: 1200),
        vsync: this,
      ),
    );

    _scaleAnimations = _controllers.map((controller) {
      return Tween<double>(begin: 0.0, end: 1.0).animate(
        CurvedAnimation(parent: controller, curve: Curves.easeOut),
      );
    }).toList();

    _opacityAnimations = _controllers.map((controller) {
      return Tween<double>(begin: 1.0, end: 0.0).animate(
        CurvedAnimation(parent: controller, curve: Curves.easeOut),
      );
    }).toList();

    _startAnimations();
  }

  void _startAnimations() {
    for (int i = 0; i < _controllers.length; i++) {
      Future.delayed(Duration(milliseconds: i * 300), () {
        if (mounted) {
          _controllers[i].repeat();
        }
      });
    }
  }

  @override
  void dispose() {
    for (final controller in _controllers) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: widget.size,
      height: widget.size,
      child: Stack(
        alignment: Alignment.center,
        children: List.generate(4, (index) {
          return AnimatedBuilder(
            animation: _controllers[index],
            builder: (context, child) {
              return Transform.scale(
                scale: _scaleAnimations[index].value,
                child: Container(
                  width: widget.size,
                  height: widget.size,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(
                      color: widget.color
                          .withOpacity(_opacityAnimations[index].value),
                      width: 2,
                    ),
                  ),
                ),
              );
            },
          );
        }),
      ),
    );
  }
}

/// 全屏加载遮罩
class LoadingOverlay extends StatelessWidget {
  final Widget child;
  final bool isLoading;
  final String? loadingText;
  final LoadingStyle loadingStyle;
  final Color? loadingColor;
  final Color? backgroundColor;

  const LoadingOverlay({
    super.key,
    required this.child,
    required this.isLoading,
    this.loadingText,
    this.loadingStyle = LoadingStyle.circular,
    this.loadingColor,
    this.backgroundColor,
  });

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        child,
        if (isLoading)
          Container(
            color: (backgroundColor ?? Colors.black).withOpacity(0.5),
            child: Center(
              child: CommonLoading(
                style: loadingStyle,
                color: loadingColor,
                text: loadingText,
                showBackground: true,
                size: LoadingSize.large,
              ),
            ),
          ),
      ],
    );
  }
}

/// 页面加载状态组件
class PageLoadingState extends StatelessWidget {
  final String? message;
  final VoidCallback? onRetry;
  final bool showRetry;

  const PageLoadingState({
    super.key,
    this.message,
    this.onRetry,
    this.showRetry = false,
  });

  @override
  Widget build(BuildContext context) {
    final themeManager = ThemeManager.instance;

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CommonLoading(
            style: LoadingStyle.circular,
            size: LoadingSize.large,
            text: message ?? '加载中...',
          ),
          if (showRetry && onRetry != null) ...[
            const SizedBox(height: 20),
            TextButton(
              onPressed: onRetry,
              child: Text(
                '重试',
                style: TextStyle(
                  color: themeManager.primaryColor,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }
}
